package com.macro.mall.commissiontask.job;

import com.macro.mall.commission.service.OrderSettleService;
import com.macro.mall.oms.entity.OrderEntity;
import com.macro.mall.oms.service.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * class
 *
 * @author xuyanjun
 * @date 2019-09-02
 */
@Slf4j(topic = "OrderSettleHandler")
@Component
public class OrderSettleHandler  {

    @Autowired
    private OrderService liveOrderService;

    @Autowired
    private OrderSettleService orderSettleService;

    public void execute() {
        LocalDateTime taskBeginTime = LocalDateTime.now();
        try {
            log.info("OrderSettleHandler begin...");

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime beginTime = now.plusHours(-12);

            List<OrderEntity> liveOrderEntities = liveOrderService.listSettlable(beginTime, now);
            if (liveOrderEntities.isEmpty()) {
                log.info("OrderSettleHandler 未找到需要结算的订单。 ");
                return;
            }

            for (OrderEntity liveOrderEntity : liveOrderEntities) {
                settleOrder(liveOrderEntity);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        long taskDuration = Duration.between(taskBeginTime, LocalDateTime.now()).toMillis();
        log.info("OrderSettleHandler end...耗时:{}毫秒 ", taskDuration);
    }

    /**
     * 结算订单
     *
     * @param liveOrder 订单
     */
    private void settleOrder(OrderEntity liveOrder) {
        LocalDateTime orderBeginTime = LocalDateTime.now();
        long orderId = liveOrder.getId();
        try {
            orderSettleService.settle(orderId);

            long duration = Duration.between(orderBeginTime, LocalDateTime.now()).toMillis();
            log.info("订单id:{}结算完成。耗时:{}毫秒", orderId, duration);
        } catch (Exception e) {
            long duration = Duration.between(orderBeginTime, LocalDateTime.now()).toMillis();

            log.error("订单id:{}结算失败。原因:{},耗时:{}毫秒", orderId, e.getMessage(), duration);
            log.error(e.getMessage(), e);
        }
    }

}
